/**
 * @program: data_structures_algorithms
 * @description: test, 必须有序
 * @author: lld
 * @create: 2020-11-15 19:18
 **/
public class BinarySearch1 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};//必须有序
        int bs = bs(arr, 0, arr.length - 1, 8);
        System.out.println(bs);
    }

    public static int bs(int[] arr, int start, int end, int num) {
//        if (start > end) {
//            return -1;
//        }
//        int mid = (start + end) / 2;
//            if (num > arr[mid]) {
//                return bs(arr, mid + 1, end, num);
//            } else if (num < arr[mid]) {
//                return bs(arr, start, mid - 1, num);
//            } else {
//                return mid;
//            }
        //非递归方法
        while (start <= end) {
            int mid = (start + end) / 2;
            if (num > arr[mid]) {
                start = mid + 1;
            } else if (num < arr[mid]) {
                end = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }


}
